//
//  RequestManager.m
//  lightSpot
//
//  Created by lightSpot  on 2022.
//  Copyright © 2022 lightSpot . All rights reserved.
//

#import "RequestManager.h"

@interface RequestManager ()

@property (nonatomic) AFHTTPSessionManager *managementSessionManager;//打点

@end

@implementation RequestManager

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        
    });
    return instance;
}

#pragma mark - 配置请求底层参数

//打点
- (AFHTTPSessionManager *)managementSessionManager {
    if (!_managementSessionManager) {
        //主Url 可以封装起来统一管理,也可以直接写在GET参数里单独管理
        NSURL *baseUrl = [NSURL URLWithString:kManagementBaseUrl];
        //AFHTTPSessionManager 创建一个网络请求
        _managementSessionManager = [[AFHTTPSessionManager manager] initWithBaseURL:baseUrl];
        _managementSessionManager.securityPolicy.allowInvalidCertificates = YES;
        _managementSessionManager.securityPolicy.validatesDomainName = NO;
        //Requests 请求Header参数
        _managementSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [_managementSessionManager.requestSerializer setValue:@"multipart/form-data; boundary=FormBoundary" forHTTPHeaderField:@"Content-Type"];
        _managementSessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _managementSessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    }
    return _managementSessionManager;
}

#pragma mark - 接口请求

//打点
- (void)saveRequestWithKey:(NSString *)key success:(void (^)(id responseObject))success failure:(void (^)(NSString *errorMsg))failure {
    
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"] boolValue]) {
        return;
    }

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *time = [formatter stringFromDate:[NSDate date]];
    
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

    [params setValue:kAppDelegate.getWorkspaceName forKey:@"sub_type"];
    [params setValue:kSafeString(kUserManager.userManager.ua) forKey:@"remark"];
    [params setValue:@"中文版" forKey:@"source"];
    [params setValue:@"/" forKey:@"uid"];
    [params setValue:localVersion forKey:@"version"];
    [params setValue:kSafeString(key) forKey:@"key"];
    [params setValue:kSafeString(time) forKey:@"event_time"];

    [params setValue:@"bvdsf3" forKey:@"dsgyj7"];
    [params setValue:@"dsjb8i" forKey:@"wfktk8"];
    [params setValue:@"IW8mkw92fg1" forKey:@"ehrj4"];
    
    [self.managementSessionManager POST:@"save.php" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [params.allKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
            [formData appendPartWithFormData:data name:key];
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"--------%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSInteger code = [dic[@"code"] integerValue];
            NSString *message = dic[@"message"];
            id data = dic[@"data"];
            if (code == 200) {
                success(data);
            } else {
                if (failure) {
                    failure(message);
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (failure) {
            failure(error.domain);
        }
    }];
}

//扩展名查询
- (void)getTargaRequestWithWord:(NSString *)word success:(void (^)(id responseObject))success failure:(void (^)(NSString *errorMsg))failure {
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"] boolValue]) {
        return;
    }

    NSMutableDictionary *querys = [[NSMutableDictionary alloc]init];

    [querys setValue:kTian_Api_Key forKey:@"key"];
    [querys setValue:kSafeString(word) forKey:@"word"];

    [self postRequestWithPath:@"targa/index" body:nil querys:querys success:^(id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSString *message) {
        if (failure) {
            failure(message);
        }
    }];
}

#pragma mark - 各种请求

//GET
- (void)postRequestWithPath:(NSString *)path body:(NSDictionary *)body querys:(id)querys success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {
    
    [self requestWithMethod:@"POST" path:path body:body querys:querys success:^(id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSString *message) {
        if (failure) {
            failure(message);
        }
    }];
}

#pragma mark - body Quer 混传

- (void)requestWithMethod:(NSString *)method path:(NSString *)path body:(id)body querys:(id)querys success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {
    NSData* bodyData;
    if (body) {
        //设置参数 根据你们服务器的格式设置。我们的后台需要传的是json格式的
        NSString *jsonString = [body mj_JSONString];
        bodyData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    }
    [self requestWithMethod:method path:path bodyData:bodyData querys:querys contentType:@"application/x-www-form-urlencoded" success:success failure:failure];
}


- (void)requestWithMethod:(NSString *)method path:(NSString *)path bodyData:(NSData *_Nullable)bodyData querys:(id)querys contentType:(NSString * _Nullable)contentType  success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *_Nullable message))failure {

    //afn请求
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    //https://api.seniverse.com/v3/weather/
    NSString *requestUrl  = [NSString stringWithFormat:@"%@/%@",kTian_Api,path];
    
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    
    //如果你不需要在请求体里传参 那就参数放入parameters里面
    NSMutableURLRequest *request = [requestSerializer requestWithMethod:method URLString:requestUrl parameters:querys error:nil];
    if (contentType) {
        [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    } else {
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    
    if (bodyData) {
        //设置参数放入到body请求体里
        [request setHTTPBody:bodyData];
    }
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/xml", @"text/plain", nil];
    manager.responseSerializer = responseSerializer;

    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSLog(@"response: %@, statusCode: %ld, %@, %@, %@", requestUrl, httpResponse.statusCode, request.allHTTPHeaderFields, querys, responseObject);
        if(error == nil) {
            if (success) {
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSInteger code = [responseObject[@"code"] integerValue];
                    if (code == 200) {
                        success(responseObject[@"result"]);
                    } else {
                        NSString *msg = responseObject[@"msg"];
                        if (failure) {
                            failure(msg);
                        }
                    }
                }
            }

        } else {
            if (failure) {
                failure(error.domain);
            }
        }

    }] resume];
}

@end

